import React, { PureComponent } from 'react';
// import { Menu } from 'antd'
import Link from 'umi/link';
// import { Tooltip } from 'antd'
import { Icon } from 'react-fa';
import Menu from './Menu';
import { /*isUrl, */ urlToList, getMenuMatches, getFlatMenus } from './utils';

const { SubMenu } = Menu;

const getSelectedMenuKeys = props => {
  const {
    location: { pathname },
    flatMenuKeys,
    flatMenus,
  } = props;
  let keys = urlToList(pathname)
    .map(itemPath => getMenuMatches(flatMenuKeys, itemPath).pop())
    .filter(item => item);

  if (keys.length) {
    const routes = keys.map(key => flatMenus[key]).filter(item => item.hide);

    // 隐藏路由时，为选中selectedKeys设置为其rootKey属性，匹配key || path属性
    if (routes.length) {
      const keys = routes.map(route => route.rootKey || route.key || route.path);

      // rootKey/key支持数组
      const flat = arr => [].concat(...arr);
      return flat(keys);
    }
  }

  return keys;
};

const getActivedMenu = data => {
  const routes = getFlatMenus(data || [], item => !item.hide);
  const keys = Object.keys(routes);
  let path;
  if (keys.length) {
    keys.some(v => {
      if (routes[v].selected) {
        path = routes[v].path;
        return true;
      }
      return false;
    });
  }
  return path;
};

export default class BaseMenu extends PureComponent {
  state = {
    openKeys: [],
  };
  getMenu = (data, parent) => {
    return (data || [])
      .filter(
        item =>
          !item.hide && (item.system || (parent ? parent.system : undefined)) === this.props.system,
      )
      .map(item => this.getSubMenuOrItem(item));
  };
  getSubMenuOrItem = item => {
    if (!item.hideMenu && item.children && item.children.length) {
      return (
        <SubMenu
          title={
            item.icon ? (
              <span className="x-menu-nav">
                {getIcon(item.icon)}
                <em>{item.name}</em>
              </span>
            ) : (
              item.name
            )
          }
          key={item.path}
        >
          {this.getMenu(item.children, item)}
        </SubMenu>
      );
    }
    let path;
    if (item.hideMenu) {
      path = getActivedMenu(item.children);
    }
    path = path || item.path;
    return (
      <Menu.Item key={item.path}>
        <Link to={path} replace>
          <span className="x-menu-nav">
            {getIcon(item.icon)}
            <em>{item.name}</em>
          </span>
        </Link>
      </Menu.Item>
    );
  };
  onOpenChange = openKeys => {
    const { flatMenuKeys, flatMenus } = this.props;

    const keys = flatMenuKeys.map(key => flatMenus[key]).filter(item => item.children);

    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);

    // 参数里含有当前二级选中项值，取最后增加进来的那个
    if (keys.indexOf(latestOpenKey) === -1) {
      this.setState({
        openKeys: [openKeys.pop()],
      });
    } else {
      this.setState({
        openKeys: latestOpenKey ? [latestOpenKey] : [],
      });
    }
  };
  render() {
    const selectedKeys = getSelectedMenuKeys(this.props);

    return (
      <>
        {this.state.openKeys.length ? (
          <Menu
            mode="inline"
            selectedKeys={selectedKeys}
            openKeys={this.state.openKeys}
            onOpenChange={this.onOpenChange}
          >
            {this.getMenu(this.props.menu)}
          </Menu>
        ) : (
          <Menu
            mode="inline"
            selectedKeys={selectedKeys}
            defaultOpenKeys={selectedKeys}
            onOpenChange={this.onOpenChange}
          >
            {this.getMenu(this.props.menu)}
          </Menu>
        )}
      </>
    );
  }
}

const getIcon = icon => {
  if (typeof icon === 'string') {
    // if (isUrl(icon)) {
    // 	return <Icon component={() => <img src={icon} alt="icon" />} />;
    // }
    return <Icon name={icon} />;
  }
  return icon;
};

// export default class BaseMenu extends PureComponent {
// 	getMenu = data => {
// 		return (data || []).map(item => this.getSubMenuOrItem(item))
// 	};
// 	getSubMenuOrItem = item => {
// 		return <li key={item.path}><Link to={item.path} className="ico-nav">{getIcon(item.icon)}<span className="ico-text">{item.name}</span></Link></li>
// 	};
// 	render() {
// 		const { menu } = this.props
// 		return (
// 			<ul>
// 				{ this.getMenu(menu) }
// 			</ul>
// 		)
// 	}
// }

// const { Item } = Menu

// export default class BaseMenu extends PureComponent {
// 	static defaultProps = {
// 		prefixCls: 'menu'
// 	}
// 	getMenu = data => {
// 		return (data || [])
// 		.filter(item => !item.hide && !item.system)
// 		.map(item => this.getSubMenuOrItem(item))
// 	};
// 	getSubMenuOrItem = item => {
// 		let path
// 		if (item.children && item.children.length) {
// 			const flatMenus = getFlatMenus(item.children, m => !m.hide)
// 			const flatArrayMenus = Object.keys(flatMenus).map(key => flatMenus[key])
// 			flatArrayMenus.some(v => {
// 				if (v.selected) {
// 					path = v.path
// 					return true
// 				}
// 				return false
// 			})
// 			// item.children.some(route => {
// 			// 	if (!route.redirect) {
// 			// 		path = route.path
// 			// 		return true
// 			// 	}
// 			// 	return false
// 			// })
// 			path = path || (flatArrayMenus.length ? flatArrayMenus[0].path : item.path)
// 		}
// 		path = path || item.path

// 		const link = <Link to={path} className="ico-nav" replace>{getIcon(item.icon)}<span className="ico-text">{item.name}</span></Link>

// 		const {
// 			tooltip
// 		} = this.props

// 		return <Item key={item.key || item.path}>{tooltip ? <Tooltip title={item.title || item.name} placement="right">{link}</Tooltip> : link}</Item>
// 	};
// 	getSelectedMenuKeys = pathname => {
// 		const {
// 			flatMenuKeys,
// 			flatMenus
// 		} = this.props;
// 		let keys = urlToList(pathname).map(itemPath => getMenuMatches(flatMenuKeys, itemPath).pop()).filter(item => item)

// 		if (keys.length) {
// 			const routes = keys.map(key => flatMenus[key]).filter(item => item.hide)
// 			// 隐藏路由时，为选中selectedKeys设置为其rootKey属性，匹配key || path属性
// 			if (routes.length) {
// 				return routes.map(route => route.rootKey || route.key || route.path)
// 			}
// 		}
// 		return keys
// 	};
// 	render() {
// 		const {
// 			menu,
// 			location: {
// 				pathname
// 			}
// 		} = this.props

// 		const selectedKeys = this.getSelectedMenuKeys(pathname)

// 		return (
// 			<Menu
// 				selectedKeys={selectedKeys}>
// 				{ this.getMenu(menu) }
// 			</Menu>
// 		)
// 	}
// }
